﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using Newtonsoft.Json;
using System.Dynamic;

namespace SaturniLibrary.Geo
{
    public class FreeGeoIp
    {
        public const string RequestFormat = "http://freegeoip.net/{0}/{1}";
    }

    public class FreeGeoIpRequestFormat
    {
        public static string Json = "json";
        public static string Csv = "csv";
        public static string Xml = "xml";

    }

    public class FreeGeoIpRequest
    {
        private string format;

        public string Format
        {
            get
            {
                if (string.IsNullOrWhiteSpace(format))
                {
                    return FreeGeoIpRequestFormat.Json;
                }
                return format;
            }
            set
            {
                format = value;
            }
        }

        public string IpOrHost { get; set; }

        public string ToRequestUrl()
        {
            return string.Format(FreeGeoIp.RequestFormat, Format, IpOrHost);
        }
    }

    public class FreeGeoIpResponse
    {
        public string Ip { get; set; }
        public string CountryCode { get; set; }
        public string CountryName { get; set; }
    }

    public class FreeGeoIpGateway
    {
        public FreeGeoIpResponse GetResponse(FreeGeoIpRequest request)
        {
            FreeGeoIpResponse response = new FreeGeoIpResponse();
            if (request != null)
            {
                try
                {
                    WebClient webClient = new WebClient();
                    string responseString = webClient.DownloadString(request.ToRequestUrl());
                    Dictionary<string, string> responseKeyValue = JsonConvert.DeserializeObject<Dictionary<string, string>>(responseString);
                    response.CountryCode = responseKeyValue["country_code"];
                    response.CountryName = responseKeyValue["country_name"];
                    response.Ip = responseKeyValue["ip"];
                }
                catch (Exception ex)
                {
                    //todo: log exception here
                    throw ex;
                }
            }
            return response;
        }
    }
}
